package com.tmt.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {

	/**
	 * 启动服务器
	 * 
	 * @throws InterruptedException
	 */
	public static void startServer() throws InterruptedException {
		EventLoopGroup group = new NioEventLoopGroup();
		ServerBootstrap sb = new ServerBootstrap();
		sb.group(group).channel(NioServerSocketChannel.class)
		.childOption(ChannelOption.AUTO_READ, false)
		.localAddress(8080)
				.childHandler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						// in 的顺序是从上往下
						// out 的顺序是从下往上
						// 但要注意触发下一个执行的时机，和执行链很像，filter 链
						ch.pipeline().addLast(new EchoServerOutHandler2());
						ch.pipeline().addLast(new EchoServerOutHandler());
						ch.pipeline().addLast(new EchoServerInHandler());
						ch.pipeline().addLast(new EchoServerInHandler2());
					}
				});
		ChannelFuture cf = sb.bind().sync();
		System.out.println("started and listen on " + cf.channel().localAddress());
		cf.channel().closeFuture().sync();
		group.shutdownGracefully().sync();
	}
	
	public static void main(String[] args) throws InterruptedException {
		startServer();
	}
}
